from flask import Flask, request, jsonify, send_from_directory
import os
import requests
import json

app = Flask(__name__, static_url_path='', static_folder='static')
UPLOAD_FOLDER = 'uploads'
os.makedirs(UPLOAD_FOLDER, exist_ok=True)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

# 1. 创建对话
def create_conversation():
    url = "https://qianfan.baidubce.com/v2/app/conversation"
    app_id = "48f36f25-98a0-4200-a1a7-9185b626800f"
    bearer = 'Bearer bce-v3/ALTAK-dqem39HTQN4Ri2TUQyaJv/ea2484e9a7c5128d727917e6375462920a84c169'
    payload = json.dumps({"app_id": app_id})
    headers = {'Content-Type': 'application/json', 'X-Appbuilder-Authorization': bearer}
    response = requests.post(url, headers=headers, data=payload)
    response_data = json.loads(response.text)
    conversation_id = response_data.get('conversation_id')
    return conversation_id

# 2. 上传图片
def upload_image(conversation_id, file):
    url = "https://qianfan.baidubce.com/v2/app/conversation/file/upload"
    app_id = "48f36f25-98a0-4200-a1a7-9185b626800f"
    bearer = 'Bearer bce-v3/ALTAK-dqem39HTQN4Ri2TUQyaJv/ea2484e9a7c5128d727917e6375462920a84c169'
    payload = {'app_id': app_id, 'conversation_id': conversation_id}
    files = [('file', (file.filename, file.read(), 'image/jpeg'))]
    headers = {'X-Appbuilder-Authorization': bearer}
    response = requests.post(url, headers=headers, data=payload, files=files)
    upload_response_data = json.loads(response.text)
    uploaded_file_id = upload_response_data.get('id')
    return uploaded_file_id

# 3. 问答消息
def get_answer(conversation_id, query, file_id):
    url = "https://qianfan.baidubce.com/v2/app/conversation/runs"
    app_id = "48f36f25-98a0-4200-a1a7-9185b626800f"
    bearer = 'Bearer bce-v3/ALTAK-dqem39HTQN4Ri2TUQyaJv/ea2484e9a7c5128d727917e6375462920a84c169'
    payload = json.dumps({
        "app_id": app_id,
        "query": query,
        "conversation_id": conversation_id,
        "stream": False,
        "file_ids": [file_id]
    })
    headers = {'Content-Type': 'application/json', 'X-Appbuilder-Authorization': bearer}
    response = requests.post(url, headers=headers, data=payload)
    response_data = json.loads(response.text)
    answer = response_data.get('answer', '未找到答案')
    return answer

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'file' not in request.files:
        return jsonify({'error': 'No file part'})
    file = request.files['file']
    if file.filename == '':
        return jsonify({'error': 'No selected file'})
    if file:
        conversation_id = create_conversation()
        if not conversation_id:
            return jsonify({'error': 'Failed to create conversation'})
        file_id = upload_image(conversation_id, file)
        if not file_id:
            return jsonify({'error': 'Failed to upload file'})
        query = request.form.get('query')
        if not query:
            return jsonify({'error': 'No query provided'})
        answer = get_answer(conversation_id, query, file_id)
        return jsonify({'answer': answer})
    return jsonify({'error': 'Unknown error'})

@app.route('/')
def index():
    return send_from_directory(app.static_folder, 'index.html')

if __name__ == '__main__':
    app.run(debug=True)